package service

import (
	"bytes"
	"github.com/astaxie/beego/logs"
	"net/http"
	"strings"
)

func PushWxMenuCreate(accessToken string, menuJsonBytes []byte) error {

	postReq, err := http.NewRequest("POST",
		strings.Join([]string{"https://api.weixin.qq.com/cgi-bin/menu/create", "?access_token=", accessToken}, ""),
		bytes.NewReader(menuJsonBytes))

	if err != nil {
		logs.Error("向微信发送菜单建立请求失败", err)
		return err
	}

	postReq.Header.Set("Content-Type", "application/json; encoding=utf-8")

	client := &http.Client{}
	resp, err := client.Do(postReq)
	if err != nil {
		logs.Error("client向微信发送菜单建立请求失败", err)
		return err
	} else {
		logs.Info("向微信发送菜单建立成功")
	}
	defer resp.Body.Close()

	return nil
}

func CreateWxMenu() error {
	menu := `{
    "button": [
        {
            "type": "miniprogram", 
            "name": "平安回家", 
            "url": "http://sqwll.zxkj.is11.com/wx/src/affirming/affirming.html?version=3", 
            "appid": "wxda6d614176de44b9", 
            "pagepath": "pages/community/index"
        }
    ]
}`
	at, _ := GetAndUpdateDBWxAToken()

	//发送建立菜单的post请求
	err := PushWxMenuCreate(at, []byte(menu))
	if err != nil {
		logs.Error("微信菜单json转换错误", err)
	}
	return nil
}
